﻿
package com.tutorial.towerofhanoi;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Random;
 
import org.andengine.audio.music.Music;
import org.andengine.audio.music.MusicFactory;
import org.andengine.audio.sound.Sound;
import org.andengine.audio.sound.SoundFactory;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.camera.hud.controls.BaseOnScreenControl;
import org.andengine.engine.camera.hud.controls.BaseOnScreenControl.IOnScreenControlListener;
import org.andengine.engine.camera.hud.controls.DigitalOnScreenControl;
import org.andengine.engine.handler.physics.PhysicsHandler;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.scene.IOnAreaTouchListener;
import org.andengine.entity.scene.ITouchArea;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.Background;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.text.Text;
import org.andengine.entity.text.TextOptions;
import org.andengine.entity.util.FPSLogger;
import org.andengine.input.touch.TouchEvent;
import org.andengine.input.touch.controller.MultiTouch;
import org.andengine.opengl.font.Font;
import org.andengine.opengl.font.FontFactory;
import org.andengine.opengl.texture.ITexture;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.bitmap.BitmapTexture;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.TextureRegionFactory;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.util.HorizontalAlign;
import org.andengine.util.adt.io.in.IInputStreamOpener;
import org.andengine.util.debug.Debug;
 
import android.graphics.Typeface;
import android.opengl.GLES20;
import android.widget.Toast;
/**
*
 * (c) 2012 Luis Velásquez 11085 and Diego Garcia 11360
*
* @author Luis Carlos Velasquez 11085 and Diego Garcia 11360
* @since 00:06:23 - 09.16.2012
*/
public class TowerOfHanoiActivity extends SimpleBaseGameActivity {
               // ===========================================================
               // Constants
               // ===========================================================
 
               private static final int CAMERA_WIDTH = 480;
               private static final int CAMERA_HEIGHT = 800;
 
               // ===========================================================
               // Fields
               // ===========================================================
 
 
              private Camera mCamera;
 
               private ITexture mTexture;
               private Font mFont;
               private BitmapTextureAtlas mBitmapTextureAtlas;
               private ITextureRegion mFaceTextureRegion;
 
               private BitmapTextureAtlas mOnScreenControlTexture;
               private BitmapTextureAtlas mBottonAtlas;
 
               private ITextureRegion mOnScreenControlBaseTextureRegion;
               private ITextureRegion mPlayButton;
              
               private ITextureRegion mOnScreenControlKnobTextureRegion;
               private DigitalOnScreenControl mDigitalOnScreenControl;
               private Sound mExplosionSound;
               private boolean mPlaceOnScreenControlsAtDifferentVerticalLocations = false;
               private Music mMusic;
 
               protected boolean mGameRunning;
               public int control=0;
               public int bandera=0;
               public String instrucciones="Instrucciones \n";
               ArrayList<Float> xCoord = new ArrayList<Float>( ) ;
               ArrayList<Float> yCoord = new ArrayList<Float>( ) ;
               // ===========================================================
               // Constructors
               // ===========================================================
 
               // ===========================================================
               // Getter & Setter
               // ===========================================================
 
               // ===========================================================
               // Methods for/from SuperClass/Interfaces
               // ===========================================================
 
               @Override
               public EngineOptions onCreateEngineOptions() {
                              this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
 
                              final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera);
                              engineOptions.getTouchOptions().setNeedsMultiTouch(true);
                              engineOptions.getAudioOptions().setNeedsSound(true);
                              engineOptions.getAudioOptions().setNeedsMusic(true);
 
                              if(MultiTouch.isSupported(this)) {
                                            if(MultiTouch.isSupportedDistinct(this)) {
                                                           Toast.makeText(this, "Traza instrucciones e intenta llegar a la meta!", Toast.LENGTH_SHORT).show();
                                            } else {
                                                           this.mPlaceOnScreenControlsAtDifferentVerticalLocations = true;
                                                           Toast.makeText(this, "MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show();
                                            }
                              } else {
                                            Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show();
                              }
 
                              return engineOptions;
               }
 
               @Override
               public void onCreateResources() {
                              BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
                              try {
                                            this.mTexture = new BitmapTexture(this.getTextureManager(), new IInputStreamOpener() {
                                                           @Override
                                                           public InputStream open() throws IOException {
                                                                          return getAssets().open("gfx/face_box.png");
                                                           }
                                            });
 
                                            this.mTexture.load();
                                            this.mFaceTextureRegion = TextureRegionFactory.extractFromTexture(this.mTexture);
                              } catch (IOException e) {
                                            Debug.e(e);
                              }
 
                              SoundFactory.setAssetBasePath("mfx/");
                              try {
                                            this.mExplosionSound = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "explosion.ogg");
                              } catch (final IOException e) {
                                            Debug.e(e);
                              }
 
 
                              MusicFactory.setAssetBasePath("mfx/");
                              try {
                                            this.mMusic = MusicFactory.createMusicFromAsset(this.mEngine.getMusicManager(), this, "pokemon.ogg");
                                            this.mMusic.setLooping(true);
                              } catch (final IOException e) {
                                            Debug.e(e);
                              }
                              this.mFont = FontFactory.create(this.getFontManager(), this.getTextureManager(), 256, 256, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 14);
                              this.mFont.load();
                              this.mBitmapTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 32, 32, TextureOptions.BILINEAR);
                              this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0);
                              this.mBitmapTextureAtlas.load();
 
                              this.mOnScreenControlTexture = new BitmapTextureAtlas(this.getTextureManager(), 256, 128, TextureOptions.BILINEAR);
                              this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0);
                              this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0);
                              this.mOnScreenControlTexture.load();
                             
                              this.mBottonAtlas = new BitmapTextureAtlas(this.getTextureManager(), 150, 150, TextureOptions.BILINEAR);
                              this.mPlayButton = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBottonAtlas, this, "play.png", 0, 0);
                              this.mBottonAtlas.load();
                             
 
               }
 
               @Override
               public Scene onCreateScene() {
                              Random generar = new Random();
                              this.mEngine.registerUpdateHandler(new FPSLogger());
 
                              final Scene scene = new Scene();
 
                              scene.setBackground(new Background(0.09804f, 0.6274f, 0.8784f));
                              TowerOfHanoiActivity.this.mMusic.play();
 
                              final float centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2;
                              final float centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2;
 
 
                              /* Create A rectangle */
                              final Rectangle[] centerRectangle = new Rectangle[20];
                              for(int r=0;r<20;r++){
                                            centerRectangle[r] = new Rectangle(generar.nextInt(15)*31+2, generar.nextInt(20)*31+32, 30, 30, this.getVertexBufferObjectManager());
 
                              scene.attachChild(centerRectangle[r]);
                              }
                              final Rectangle  meta= new Rectangle(generar.nextInt(15)*31+2, generar.nextInt(20)*31+32, 30, 30, this.getVertexBufferObjectManager());
                              scene.attachChild(meta);
 
                             
 
                              final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion, this.getVertexBufferObjectManager());
                              final PhysicsHandler physicsHandler = new PhysicsHandler(face);
 
                             
                              scene.attachChild(face);
                              final Sprite play = new Sprite(315, 650, this.mPlayButton, this.getVertexBufferObjectManager());
                              scene.attachChild(play);
                             
 
              
                              final VertexBufferObjectManager vertexBufferObjectManager = this.getVertexBufferObjectManager();
                              final Text centerText = new Text(185,650, this.mFont, "Hello AndEngine!\nYou can even have multilined text!", new TextOptions(HorizontalAlign.CENTER), vertexBufferObjectManager);                             
                              this.mDigitalOnScreenControl = new DigitalOnScreenControl(0, CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(), this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, this.getVertexBufferObjectManager(), new IOnScreenControlListener() {
                                           
                                            @Override
                                            public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) {
                                                           if((pValueX!=0.0)||(pValueY!=0.0)){
                                                          
                                                           xCoord.add(pValueX);
                                                           yCoord.add(pValueY);}
                                                           if(instrucciones.length()%11==0)
                                                                          instrucciones+="\n";
                                                           if(pValueY==-1.0)
                                                                          instrucciones+="↑ ";
                                                           if(pValueY==1.0)
                                                                          instrucciones+="↓ ";
                                                           if(pValueX==-1.0)
                                                                          instrucciones+="← ";
                                                           if(pValueX==1.0)
                                                                          instrucciones+="→ ";
                                                           centerText.setText(instrucciones);
 
                                           
                                                          
                                            }
                              });
                              this.mDigitalOnScreenControl.getControlBase().setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
                              this.mDigitalOnScreenControl.getControlBase().setAlpha(0.5f);
                              this.mDigitalOnScreenControl.getControlBase().setScaleCenter(0, 128);
                              this.mDigitalOnScreenControl.getControlBase().setScale(1.25f);
                              this.mDigitalOnScreenControl.getControlKnob().setScale(1.25f);
                              this.mDigitalOnScreenControl.refreshControlKnobPosition();
                             
 
                              scene.setChildScene(this.mDigitalOnScreenControl);
                             
                             
                             
                              scene.setOnAreaTouchListener(new IOnAreaTouchListener() {
                                            @Override
                                            public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
                                            if(pSceneTouchEvent.isActionDown()) {
                                                           TowerOfHanoiActivity.this.mGameRunning = true;
                                                           bandera=1;
                                            }
                                            return true;
                                            }
                                            });
                              scene.registerTouchArea(play);
                             
 
 
 
                             
                              scene.attachChild(centerText);
 
 
                              scene.registerUpdateHandler(new TimerHandler(1.0f, true, new ITimerCallback() {
 
                                            int iniy=0;
                                            int inix=0;
                                                          
 
                                           
 
                                            @Override
                                            public  void onTimePassed(final TimerHandler pTimerHandler) {
                                                          
                                                           if((bandera!=0)&&(TowerOfHanoiActivity.this.mGameRunning))
                                                           {
                                                                          if(control<(yCoord.size()-1))
                                                                          face.setPosition(inix+=xCoord.get(control)*32, iniy+=yCoord.get(control)*32);
                                                           }            
 
                                                           for(int r=0;r<20;r++){
                                                           if(centerRectangle[r].collidesWith(face)) {
                                                                          TowerOfHanoiActivity.this.mExplosionSound.play();
                                                                          centerRectangle[r].setColor(1, 0, 0);
                                                                          yCoord.clear();
                                                                          xCoord.clear();
                                                                          iniy=0;
                                                                          inix=0;
                                                                          bandera=0;
                                                                          control=0;
                                                                          face.setPosition(0, 0);
                                                                          instrucciones="Instrucciones\n ";
                                                                          gameToast("Has choqado intentalo de nuevo!");
                                                   
                                                                         
                                                                          TowerOfHanoiActivity.this.mGameRunning = false;
                                                           } else {
                                                                          centerRectangle[r].setColor(0, 1, 0);
                                                           }
                                                           if(meta.collidesWith(face)) {
                                                                         
                                                                          meta.setColor(1, 0, 1);
                                                                          yCoord.clear();
                                                                          xCoord.clear();
                                                                          iniy=0;
                                                                          inix=0;
                                                                          bandera=0;
                                                                          control=0;
                                                                          face.setPosition(0, 0);
                                                                          instrucciones="Instrucciones\n ";
                                                                          gameToast("Felicitaciones lo lograste!");
                                                   
                                                                         
                                                                          TowerOfHanoiActivity.this.mGameRunning = false;
                                                           } else {
                                                                          meta.setColor(0, 1, 1);
                                                           }
                                                           if(!mCamera.isRectangularShapeVisible(face)) {
                                                                          centerRectangle[r].setColor(1, 0, 1);
                                                                          gameToast("Te has salido del area de juego, vuelve a intentar");
                                                                          yCoord.clear();
                                                                          xCoord.clear();
                                                                          iniy=0;
                                                                          inix=0;
                                                                          bandera=0;
                                                                          control=0;
                                                                          face.setPosition(0, 0);
                                                                          instrucciones="Instrucciones\n ";
                                                           }
                                                           }
 
 
                                                           if((bandera!=0)&&(TowerOfHanoiActivity.this.mGameRunning))
                                                            control++;
                                            }
                                           
                              }));
 
                              return scene;
                             
                             
              
               }
              
               public void gameToast(final String msg) {
                                                this.runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                       Toast.makeText(TowerOfHanoiActivity.this, msg, Toast.LENGTH_SHORT).show();
                                                    }
                                                });
                                            }
               // ===========================================================
               // Methods
               // ===========================================================
 
               // ===========================================================
               // Inner and Anonymous Classes
               // ===========================================================
}
